import { defineStore } from "pinia";

import {
    memberManageLogin,
    getMemberUserInfo,
    type LoginByAccountParams,
    type MemberManageLoginResponse,
} from "@/services/account";
import crypto from "@/utils/crypto";
import router from "@/router";

import { useMenuStore } from "./menu";
import { useTagsStore } from "./tags";

const AUTH_TOKEN_KEY = "user-auth-token";

export const useUserStore = defineStore("user", {
    state: (): MemberManageLoginResponse => ({
        userId: 0,
        memberId: 0,
        memberRoleId: 0,
        token: localStorage.getItem(AUTH_TOKEN_KEY) || "",
        account: "",
        name: "",
        tokenExpireMinutes: 0,
        urls: [],
    }),
    actions: {
        async getUserInfo() {
            const res = await getMemberUserInfo();
            if (!res) return null;

            this.$patch(res);
            return res;
        },
        async login(params: LoginByAccountParams) {
            params.password = crypto(params.password);
            const token = await memberManageLogin(params);
            if (!token) return null;

            localStorage.setItem(AUTH_TOKEN_KEY, token);
            this.$patch({ token });

            return token;
        },
        logout() {
            const menu = useMenuStore();
            const tags = useTagsStore();

            menu.reset();
            tags.$reset();
            this.$reset();
            localStorage.removeItem(AUTH_TOKEN_KEY);
            router.replace("/login");
        },
    },
});
